<?php
/**
 * Author: Silent Night
 * email: silentwolf_wp@163.com
 * Date: 2017/10/10
 * Time: 11:02
 */

namespace app\admin\model;

use think\Model;

class BaseModel extends Model
{
    /**
     * 更具ID获取一条数据
     * @param $id
     * @param string $fields
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getID($id, $fields = "*")
    {
        $data = array();
        $res = $this->field($fields)->where(['id' => $id])
            ->find();
        if ($res) {
            $data = $res->toArray();
        }
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $data;
    }


    /**
     * 根据条件获取1条数据
     * @param $w
     * @param string $fields
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDataForWhere($w, $fields = "*", $orderby = "")
    {
        $data = array();
        $this->field($fields)->where($w);
        if (!empty($orderby)) {
            $this->order($orderby);
        }
        $res = $this->find();
        if ($res) {
            $data = $res->toArray();
        }
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $data;
    }

    /**
     * 根据条件统计一个字段的数据的总和
     * @param $w
     * @param $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSumFieldForWheres($w, $field)
    {
        $totle = $this->where($w)->sum($field);
        return empty($totle) ? 0 : $totle;
    }

    /**
     * 根据条件获取多条数据
     * @param $w
     * @param string $fields
     * @param string $orderby
     * @param string $limit 查询限定条数 默认不限定
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDataForWheres($w, $fields = "*", $orderby = "id desc", $limit = '0')
    {
        $data = array();
        $this->field($fields)->where($w)->order($orderby);
        if (!empty($limit)) {
            $this->limit(0, $limit);
        }
        $res = $this->select();
        if ($res) {
            $data = $res->toArray();
        }
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $data;
    }

    /**
     * 根据ID更新数据
     * @param $update
     * @param $id
     * @return false|int
     */
    public function updateData($update, $id)
    {
        $res = $this->save($update, ['id' => $id]);
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $res;
    }

    /**
     * 根据条件更新数据
     * @param $update
     * @param $where
     * @return false|int
     */
    public function updateDataForWhere($update, $where)
    {
        $res = $this->save($update, $where);
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $res;
    }

    /**
     * 插入1条数据
     * @param $array
     * @return string
     */
    public function add($array)
    {
        $this->save($array);
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $this->getLastInsID();
    }

    /**循环连续插入多条数据，并取的每条插入的ID
     * @param $array
     * @return string
     */
    public function addExp($array)
    {
        $this->data($array, true)->isUpdate(false)->save();
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $this->getLastInsID();
    }

    /**
     * 一次性插入多条数据
     * @param $array =[$data,$data,$data]
     * @return string
     */
    public function addAll($array)
    {
        return $this->saveAll($array);
    }

    /**
     * 根据条件删除数据
     * @param $w
     * @return int
     */
    public function delData($w)
    {
        $result = $this->where($w)->delete();
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $result;
    }

    /**
     * 自定义分页列表查询函数（详细）
     * @param $sql
     * @param string $pagesize 每页条数
     * @param int $page 当前页面
     * @return array
     */
    public function listsForSQL($sql, $pagesize = "10", $page = 1)
    {
        $allList = \think\Db::query($sql);
        $total = 0;//总条数
        $last_page = 0;//最大页码
        if ($allList) {
            $total = count($allList);
            $last_page = ceil($total / $pagesize);
        }
        $start = ($page - 1) * $pagesize;
        $sql = $sql . " limit " . $start . "," . $pagesize;
        $List = \think\Db::query($sql);
        $resultData = array(
            'total' => $total,//总条数
            'per_page' => $pagesize,//每页条数
            'current_page' => $page,//当前页码
            'last_page' => $last_page,//最大页码
            'data' => $List,//数据
        );
        return $resultData;
    }


    /**
     * 自定义简单分页列表查询函数（主要用于接口上拉分页使用）,该接口不返回总条数 总页数等数据
     * @param $sql
     * @param string $pagesize 每页条数
     * @param int $page 当前页面
     * @return array
     */
    public function listsSimpleForSQL($sql, $pagesize = "10", $page = 1)
    {
        $start = ($page - 1) * $pagesize;
        $sql = $sql . " limit " . $start . "," . $pagesize;
        $Lists = \think\Db::query($sql);
        return $Lists;
    }

    /**
     * 系统默认分页查询函数（详细）
     * @param $w
     * @param string $pagesize
     * @param string $fields
     * @param string $orderby
     * @return array
     * @throws \think\exception\DbException
     */
    public function lists($w, $pagesize = "10", $fields = "*", $orderby = "id desc")
    {
        if (!empty($w)) {
            $this->where($w);
        }
        $list = $this->field($fields)->order($orderby)->paginate($pagesize)->toArray();
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $list;
    }

    public function listsNorepeat($w, $pagesize = "10", $fields = "*", $orderby = "id desc", $norepeatField = '')
    {
        if (!empty($w)) {
            $this->where($w);
        }
        if ($norepeatField) {
            $list = $this->group($norepeatField)->field($fields)->order($orderby)->paginate($pagesize)->toArray();
        } else {
            $list = $this->field($fields)->order($orderby)->paginate($pagesize)->toArray();
        }
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $list;
    }

    /**
     * 执行update insert 和delete等操作的函数
     * @param $sql
     * @return int 返回 影响行数
     */
    public function executeSQL($sql)
    {
        $result = \think\Db::execute($sql);
        return $result;
    }

    /**
     * 直接执行查询sql
     * @param $sql
     * @return mixed
     */
    function querySelectSQL($sql)
    {
        $result = \think\Db::query($sql);
        return $result;
    }

    /**
     * 设置一个字段自动减少
     * @param $w 条件
     * @param $field 操作字段
     * @param int $num 步长
     * @return int|true
     * @throws \think\Exception
     */
    function updateForDec($w, $field, $num = 1)
    {
        $flag = $this->where($w)
            ->setDec($field, $num);
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $flag;
    }

    /**
     * 设置一个字段自动增加
     * @param $w
     * @param $field
     * @param int $num
     * @return int|true
     * @throws \think\Exception
     */
    function updateForInc($w, $field, $num = 1)
    {
        $flag = $this->where($w)
            ->setInc($field, $num);
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $flag;
    }

    /**
     * @title 求一个条件的查询总条数
     * @description 统计总条数
     * @param $w 查询条件
     * @return int|true
     * @throws \think\Exception
     */
    function getCount($w = array())
    {
        $res = $this->where($w)->count();
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $res;
    }

    /**
     * @title 查询指定字段的最大值
     * @param array $w 条件
     * @param string $field 字段
     * @return mixed
     */
    function getMax($w = array(), $field = 'id')
    {
        $res = $this->where($w)->max($field);
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $res;
    }

    /**
     * @title 查询指定字段的最小值
     * @param array $w 条件
     * @param string $field 字段
     * @return mixed
     */
    function getMin($w = array(), $field = 'id')
    {
        $res = $this->where($w)->min($field);
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $res;
    }


    /**
     * @title 查询指定字段的总和
     * @param array $w 条件
     * @param string $field 字段
     * @return mixed
     */
    function getSum($w = array(), $field = 'id')
    {
        $res = $this->where($w)->sum($field);
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $res;
    }

    /**
     * @title 查询指定字段的平均值
     * @param array $w 条件
     * @param string $field 字段
     * @return mixed
     */
    function getAvg($w = array(), $field = 'id')
    {
        $res = $this->where($w)->avg($field);
        if ($_REQUEST['debug']) {
            echo $this->getLastSql() . "<br>";
        }
        return $res;
    }
}